//
//  UIImageView+DownCache.m
//  HomeWork
//
//  Created by apple on 2017/10/26.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "UIImageView+DownCache.h"

@implementation UIImageView (DownCache)

- (void)setImageWithUrl:(NSString *)url{
    return [self setImageWithUrl:url placeholderImage:nil];
}

- (void)setImageWithUrl:(NSString *)url placeholderImage:(UIImage *)placeholder{
    return [self setImageWithURL:url placeholderImage:placeholder completed:nil];
}

- (void)setImageWithURL:(NSString *)url placeholderImage:(UIImage *)placeholder completed:(CompletionBlock)completedBlock{
    
    [self setImage:placeholder imageData:nil];
    
    if (!url.length) {
        return;
    }
    
    [[[HWDownloader alloc] init] downloadWithUrl:[NSURL URLWithString:url] completion:^(UIImage * _Nullable image, NSError * _Nullable error, NSURL * _Nullable imageURL) {
        if (!error) {
            [self setImage:image imageData:nil];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completedBlock) {
                completedBlock(image, error, imageURL);
            }
        });
    }];
    
}
// 设置图片
- (void)setImage:(UIImage *)image imageData:(NSData *)imageData {
    if (!image && !imageData) {
        return;
    }
    if (!image) {
        image = [UIImage imageWithData:imageData];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([self isKindOfClass:[UIImageView class]]) {
            UIImageView *imageView = (UIImageView *)self;
            imageView.image = image;
        }
        [self setNeedsLayout];
    });
    
}

@end
